from sqlalchemy.orm import Session
from app.database.database import SessionLocal, engine, Base
from app.models.models import SysUser, SysMenu
from app.utils.auth import get_password_hash
import datetime

# 创建数据库表
Base.metadata.create_all(bind=engine)

def init_admin_user():
    db = SessionLocal()
    try:
        # 检查是否已存在管理员
        admin = db.query(SysUser).filter(SysUser.name == "admin").first()
        if not admin:
            # 创建管理员用户
            hashed_password = get_password_hash("admin")
            admin_user = SysUser(
                name="admin",
                email="admin@example.com",
                password=hashed_password,
                remark="系统管理员",
                is_admin=1,
                is_active=1,
                created_at=datetime.datetime.utcnow(),
                updated_at=datetime.datetime.utcnow()
            )
            db.add(admin_user)
            print("✅ 管理员用户已创建")
        else:
            print("⚠️ 管理员用户已存在，跳过创建")
            
        # 添加基本菜单
        menus = [
            {
                "id": 1,
                "pid": 0,
                "name": "系统管理",
                "icon": "bi-grid",
                "code": "system",
                "path": "#",
                "is_active": 1
            },
            {
                "id": 2,
                "pid": 1,
                "name": "用户管理",
                "icon": "bi-person",
                "code": "user:list",
                "path": "/admin/users",
                "is_active": 1
            },
            {
                "id": 3,
                "pid": 1,
                "name": "菜单管理",
                "icon": "bi-list",
                "code": "menu:list",
                "path": "/admin/menus",
                "is_active": 1
            }
        ]
        
        for menu_data in menus:
            menu = db.query(SysMenu).filter(SysMenu.id == menu_data["id"]).first()
            if not menu:
                menu = SysMenu(
                    id=menu_data["id"],
                    pid=menu_data["pid"],
                    name=menu_data["name"],
                    icon=menu_data["icon"],
                    code=menu_data["code"],
                    path=menu_data["path"],
                    is_active=menu_data["is_active"],
                    created_at=datetime.datetime.utcnow(),
                    updated_at=datetime.datetime.utcnow()
                )
                db.add(menu)
                print(f"✅ 菜单 '{menu_data['name']}' 已创建")
            else:
                print(f"⚠️ 菜单 '{menu_data['name']}' 已存在，跳过创建")
        
        db.commit()
        print("✅ 数据库初始化完成")
        
    except Exception as e:
        db.rollback()
        print(f"❌ 初始化数据库失败: {str(e)}")
    finally:
        db.close()

if __name__ == "__main__":
    init_admin_user() 

    print(get_password_hash("admin")) # 输出加密后的密码
